package com.puman.watchtrade;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.animation.AlphaAnimation;
import android.view.animation.AnimationSet;
import android.view.Window;
import android.webkit.ValueCallback;
import android.widget.ImageButton;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;

import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.jeremyfeinstein.slidingmenu.lib.app.SlidingFragmentActivity;
import com.puman.watchtrade.fragment.LeftCategoryFragment;
import com.puman.watchtrade.fragment.home.GoodsDetailFragment;
import com.puman.watchtrade.fragment.home.HomeFragment;
import com.puman.watchtrade.fragment.home.VarietiesListFragment;
import com.puman.watchtrade.fragment.home.imageLoader.util.CheckImageLoaderConfiguration;
import com.puman.watchtrade.fragment.set.LoginFragment;
import com.puman.watchtrade.fragment.set.httpHandler.SettingHttpHandler;
import com.puman.watchtrade.util.DataResult;
import com.puman.watchtrade.util.Gjfun;
import com.puman.watchtrade.util.GlobalData;
import com.puman.watchtrade.util.ImageDownloader;
import com.puman.watchtrade.util.MinPriorityThreadFactory;
import com.puman.watchtrade.util.Save;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.umeng.socialize.sso.UMQQSsoHandler;
import com.umeng.update.UmengUpdateAgent;

@SuppressLint("NewApi")
public class MainActivity extends SlidingFragmentActivity {

	public ViewPager myViewPager;
	private Fragment mContent;
	public static FragmentManager fragmentManager;
	static MainActivity mainActivity;

	public ValueCallback<Uri> mUploadMessage;
	public final static int FILECHOOSER_RESULTCODE = 1;

	private boolean isExit = false;
	public static final int EXIT_APP = 0x11;
	public static final int OUT_APP = 0x13;
	public static final int UNREGISTER = 0x12;
	private static final int LOGIN_SUC = 0x1;
	private static final int LOGIN_FAIL = 0x2;

	public TextView topTitle;
	private ImageButton main_left_imgbtn;
	public Display display;

	private static MainActivity myInstant;

	public LocationManager locationManager;
	public ImageDownloader mDownloader;

	public static boolean isForeground = false;
	public List<Bitmap> bitMap = new ArrayList<Bitmap>();
	public int sdk = android.os.Build.VERSION.SDK_INT;
	public List<String> tagList = new ArrayList<String>();

	public ExecutorService cachedThreadPoolMinPriority = Executors
			.newCachedThreadPool(new MinPriorityThreadFactory());
	public static Save save = new Save();

	public static SlidingMenu slidingMenu;

	public OnekeyShare oks;

	public ExecutorService getCachedThreadPoolMinPriority() {
		return cachedThreadPoolMinPriority;
	}

	public void setCachedThreadPoolMinPriority(
			ExecutorService cachedThreadPoolMinPriority) {
		this.cachedThreadPoolMinPriority = cachedThreadPoolMinPriority;
	}

	public MySetOnClickListener mySetOnClickListener = new MySetOnClickListener();

	public static MainActivity getInstant() {
		return myInstant;
	}

	public static SlidingMenu getSlidingmunu() {
		return slidingMenu;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		GlobalData.screenWidth = dm.widthPixels;
		GlobalData.screenHeight = dm.heightPixels;
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		myInstant = this;
		mainActivity = this;

		display = getWindowManager().getDefaultDisplay();
		// final UMSocialService mController = UMServiceFactory
		// .getUMSocialService("com.umeng.share", RequestType.SOCIAL);
		UmengUpdateAgent.update(this);
		UmengUpdateAgent.setUpdateOnlyWifi(false);

		registerAlisePush();

		setContentView(R.layout.main);
		initSlidingMenu(savedInstanceState);
		fragmentManager.beginTransaction()
				.replace(R.id.main_non_bottom, new HomeFragment()).commit();

//		initView();
		ShareSDK.initSDK(mainActivity);
		oks = new OnekeyShare();

		oks.setTitle(getString(R.string.app_name));
		oks.setTitleUrl("http://www.huimaionline.com");
		oks.setText("要会卖，更要会麦");
		oks.setUrl("http://www.huimaionline.com");
		oks.setComment("要会卖，更要会麦");
		oks.setSite(getString(R.string.app_name));
		oks.setSiteUrl("http://www.huimaionline.com");
		// // 启动分享GUI
		// initUmeng();
		// GlobalData.userInfo.getAddress();
		GlobalData.statusBarHeight = Gjfun.getStatusBarHeight(this);
		// 初始化图片类
		CheckImageLoaderConfiguration
				.checkImageLoaderConfiguration(MainActivity.getInstant());
		sharedPreferences = getInstant().getSharedPreferences("watchtrade",
				Context.MODE_PRIVATE);
		editor = sharedPreferences.edit();// 获取编辑器
		// MainActivity.getInstant().registerAlisePush();
		autoLogin();

		// /*
		// * 设置动画
		// */

		Uri uri = getIntent().getData();
		if (uri != null) {
			StringBuffer sb = new StringBuffer();
			// 完整的url信息
			sb.append("url: " + uri.toString());
			// scheme部分
			sb.append("\nscheme: " + uri.getScheme());
			// host部分
			sb.append("\nhost: " + uri.getHost());
			// 访问路劲
			sb.append("\npath: ");
			List<String> pathSegments = uri.getPathSegments();
			for (int i = 0; pathSegments != null && i < pathSegments.size(); i++) {
				sb.append("/" + pathSegments.get(i));
			}
			// Query部分
			sb.append("\nquery: " + uri.getQuery());
			List<String> mapList = new ArrayList<String>();
			mapList = URLRequest(uri.getQuery());

			FragmentTransaction transaction = MainActivity.fragmentManager
					.beginTransaction();
			GoodsDetailFragment goodsDetailFragment = new GoodsDetailFragment(
					mapList.get(0), mapList.get(1));
			transaction.replace(R.id.main_non_bottom, goodsDetailFragment);
			transaction.addToBackStack(null);
			transaction.commit();
		}

	}

	/**
	 * 解析出url参数中的键值对 如 "index.jsp?Action=del&id=123"，解析出Action:del,id:123存入map中
	 * 
	 * @param URL
	 *            url地址
	 * @return url请求参数部分
	 */
	public static List<String> URLRequest(String URL) {
		List<String> mapList = new ArrayList<String>();
		String[] arrSplit = null;
		// 每个键值为一组 www.2cto.com
		arrSplit = URL.split("[&]");
		for (String strSplit : arrSplit) {
			String[] arrSplitEqual = null;
			arrSplitEqual = strSplit.split("[=]");
			// 正确解析
			if (arrSplitEqual[0].equals("goodsNo")) {
				mapList.add(0, arrSplitEqual[1]);
			} else if (arrSplitEqual[0].equals("inWitch")) {
				mapList.add(1, arrSplitEqual[1]);
			}
		}
		return mapList;

	}

	// public static AlphaAnimation alphaAnimation;
	// public static AnimationSet animationalpha;

	private SharedPreferences sharedPreferences; // 私有数据
	private Editor editor;
	/**
	 * 自动登录
	 */
	private String mobile;
	private String password;

	private void autoLogin() {
		if (sharedPreferences.getString("mobile", "").equals("")
				|| sharedPreferences.getString("password", "").equals("")) {
			// Toast.makeText(MainActivity.getInstant(), "自动登录失败1",
			// Toast.LENGTH_SHORT).show();
			return;
		}
		mobile = sharedPreferences.getString("mobile", "");
		password = sharedPreferences.getString("password", "");
		cachedThreadPoolMinPriority.execute(autoLoginRunnable);
	}

	Runnable autoLoginRunnable = new Runnable() {

		@Override
		public void run() {
			int what = LOGIN_FAIL;
			dataResult = null;
			dataResult = new DataResult();
			Log.i("curry", "mobile:" + mobile);
			Log.i("curry", "password:" + password);
			dataResult = settingHttpHandler.login(mobile, password);
			if (dataResult.flag) {
				what = LOGIN_SUC;
			}
			sendMessage(what);
		}
	};

	private void sendMessage(int what) {
		Message msg = new Message();
		msg.what = what;
		handler.sendMessage(msg);
	}


	public IWXAPI api;

	// public static UMSocialService mController;

	private void initUmeng() {
		UmengUpdateAgent.setUpdateOnlyWifi(false);
		UmengUpdateAgent.update(this);
	}

	/**
	 * 初始化SlidingMenu
	 */
	private void initSlidingMenu(Bundle savedInstanceState) {
		slidingMenu = getSlidingMenu();
		if (savedInstanceState != null) {
			mContent = getSupportFragmentManager().getFragment(
					savedInstanceState, "mContent");
		}
		if (mContent == null) {
			mContent = new HomeFragment();
		}
		fragmentManager = getSupportFragmentManager();

		setBehindContentView(R.layout.left_content);
		fragmentManager.beginTransaction()
				.replace(R.id.left_content_id, new LeftCategoryFragment())
				.commit();

		getSlidingMenu().setMode(SlidingMenu.LEFT);
		getSlidingMenu().setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);
		getSlidingMenu().setShadowWidthRes(R.dimen.shadow_width);
		getSlidingMenu().setShadowDrawable(R.drawable.shadow);
		getSlidingMenu().setBehindOffsetRes(R.dimen.slidingmenu_offset);
		getSlidingMenu().setFadeDegree(0.35f);
		getSlidingMenu().setBehindOffset((int) (display.getWidth() / 1.7));
		getSlidingMenu().setSlidingEnabled(true);
	}

	/**
	 */
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		// getSupportFragmentManager().putFragment(outState, "mContent",
		// mContent);
	}

	public void initView() {
		FragmentTransaction transaction = MainActivity.fragmentManager
				.beginTransaction();
		HomeFragment homeFragment = new HomeFragment();
		transaction.replace(R.id.main_non_bottom, homeFragment);
		transaction.addToBackStack(null);
		transaction.commit();
	}

	/**
	 * 
	 * @author curry
	 * 
	 */
	public class MySetOnClickListener implements OnClickListener {

		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.main_left_imgbtn:
				toggle();
				break;
			default:
				break;
			}

		}

	}

	/**
	 * ͷ��������
	 */
	public class MyOnClickListener implements View.OnClickListener {
		private int index = 0;

		public MyOnClickListener(int i) {
			index = i;
		}

		@Override
		public void onClick(View v) {
			myViewPager.setCurrentItem(index);

		}
	};

	/**
	 * �л���ͼ
	 * 
	 * @param fragment
	 */
	public void switchContent(Fragment fragment) {
		mContent = fragment;
		getSlidingMenu().showContent();
	}

	Callback callback = new Callback() {
		@Override
		public boolean handleMessage(Message msg) {
			// TODO Auto-generated method stub
			switch (msg.what) {
			case EXIT_APP:
				isExit = false;
				break;
			case UNREGISTER:
				// isExit = false;
				break;
			case OUT_APP:
				System.exit(0);
			case LOGIN_SUC:
				Toast.makeText(MainActivity.getInstant(), "自动登录成功",
						Toast.LENGTH_SHORT).show();
				if (GlobalData.userInfo != null) {
					if (!GlobalData.userInfo.getNick().equals("")) {
						LeftCategoryFragment.userName
								.setText(GlobalData.userInfo.getNick());
					} else {
						LeftCategoryFragment.userName
								.setText(GlobalData.userInfo.getMobile());
					}
					LeftCategoryFragment.loginBtnInfo.setText("退出");
				}
				break;
			case LOGIN_FAIL:
				Toast.makeText(MainActivity.getInstant(), "自动登录失败",
						Toast.LENGTH_SHORT).show();
				break;
			default:
				break;
			}
			return false;
		}
	};

	Handler handler = new Handler(callback);

	private void sendMesDelay(int what, int delay) {
		Message msg = new Message();
		msg.what = what;
		handler.sendMessageDelayed(msg, delay);
	}

	public void exit() {
		if (!isExit) {
			isExit = true;
			Toast.makeText(getApplicationContext(), "再按一次退出程序",
					Toast.LENGTH_SHORT).show();
			sendMesDelay(EXIT_APP, 1500);
		} else {
			Intent intent = new Intent(Intent.ACTION_MAIN); // ָ
			intent.addCategory(Intent.CATEGORY_HOME);
			startActivity(intent);
			// GlobalData.userInfo = null;
			unRegister();
			// sendMesDelay(OUT_APP, 1000);
			// System.exit(0);
		}
	}

	private void unRegister() {
		cachedThreadPoolMinPriority.execute(unregisterRunnable);
	}

	private SettingHttpHandler settingHttpHandler = new SettingHttpHandler();
	private DataResult dataResult = new DataResult();
	/*
	 * 登录
	 */
	Runnable unregisterRunnable = new Runnable() {

		@Override
		public void run() {
			int what = OUT_APP;
			dataResult = settingHttpHandler.loginOut();
			// if (dataResult.flag) {
			// what = LOGIN_SUC;
			// }
			sendMesDelay(what, 0);
		}
	};

	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (fragmentManager.getBackStackEntryCount() == 1) {
				MainActivity.getInstant().getSlidingMenu()
						.setSlidingEnabled(true);
			}
			if (fragmentManager.getBackStackEntryCount() == 0) {
				exit();
				return false;
			} else {
				String name = fragmentManager.getBackStackEntryAt(
						fragmentManager.getBackStackEntryCount() - 1).getName();
				if (name != null && name.equals("varietiesListFragment")) {
					VarietiesListFragment.currIndex = 0;
					fragmentManager.popBackStack();
				} else {
					fragmentManager.popBackStack();
				}
				return false;
			}

		} else {
			return super.onKeyDown(keyCode, event);
		}
	}

	static class DummyTabFactory implements TabHost.TabContentFactory {
		private final Context mContext;

		public DummyTabFactory(Context context) {
			mContext = context;
		}

		@Override
		public View createTabContent(String tag) {
			View v = new View(mContext);
			v.setMinimumWidth(0);
			v.setMinimumHeight(0);
			return v;
		}
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		isForeground = true;
		JPushInterface.onResume(MainActivity.getInstant());
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		isForeground = false;
		JPushInterface.onPause(MainActivity.getInstant());
	}

	/**
	 * 注册推送
	 */
	public void registerAlisePush() {
		TelephonyManager TelephonyMgr = (TelephonyManager) MainActivity
				.getInstant().getSystemService("phone");
		String szImei = TelephonyMgr.getDeviceId();
		Log.i("curry", "uid:" + szImei);
		GlobalData.deviceNo = szImei;
		JPushInterface.setAlias(MainActivity.getInstant(), GlobalData.deviceNo,
				new TagAliasCallback() {

					@Override
					public void gotResult(int code, String arg1,
							Set<String> arg2) {
						// TODO Auto-generated method stub
						String logs;
						String TAG = "curry";
						switch (code) {
						case 0:
							logs = "Set tag and alias success";
							Log.i(TAG, logs);
							// 建议这里往 SharePreference
							// 里写一个成功设置的状态。成功设置一次后，以后不必再次设置了。
							break;
						case 6002:
							logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
							Log.i(TAG, logs);
							// 延迟 60 秒来调用 Handler 设置别名
							// mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS,
							// alias), 1000 * 60);
							break;
						default:
							logs = "Failed with errorCode = " + code;
							Log.i(TAG, logs);
						}
					}
				});
	}

	public static AlertDialog alertDialog;

	public static void reLogin(String info) {
		alertDialog = new AlertDialog.Builder(MainActivity.getInstant())
				.create();
		alertDialog.show();
		alertDialog.setCanceledOnTouchOutside(false);
		Window window = alertDialog.getWindow();
		window.setContentView(R.layout.relogin_dialog);
		window.clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);// ��������n
		TextView sureBtn = (TextView) window.findViewById(R.id.sure_btn);
		final TextView infoDetail = (TextView) window
				.findViewById(R.id.info_detail);
		infoDetail.setText(info);

		sureBtn.setBackgroundColor(MainActivity.getInstant().getResources()
				.getColor(R.color.themeColor));
		sureBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				alertDialog.dismiss();
				GlobalData.isAlertShow = false;
				FragmentTransaction transaction = MainActivity.fragmentManager
						.beginTransaction();
				LoginFragment loginFragment = new LoginFragment();
				transaction.replace(R.id.main_non_bottom, loginFragment);
				transaction.addToBackStack(null);
				transaction.commit();
			}
		});
	}
}
